<?php
$page_title = "注册";
session_start();
include 'template/header.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	require 'mysqli_connect.php';
	$errors = array();
	if (empty($_POST['first_name'])) {
		$errors[] = '未输入名字';
	} else {
		$fn = mysqli_real_escape_string($dbc, $_POST['first_name']);
	}
	if (empty($_POST['last_name'])) {
		$errors[] = '未输入姓氏';
	} else {
		$ln = mysqli_real_escape_string($dbc, $_POST['last_name']);
	}
	if (empty($_POST['email'])) {
		$errors[] = '未输入邮箱';
	} else {
		$em = mysqli_real_escape_string($dbc, $_POST['email']);
	}
	if (empty($_POST['pass1'])) {
		$errors[] = '未输入密码';
	} else if (empty($_POST['pass2'])) {
		$errors[] = '请再次输入密码以确认';
	} else if ($_POST['pass1'] != $_POST['pass2']) {
		$errors[] = '两次输入的密码不一致';
	} else {
		// 保存密码字串
		$p = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
	}
	// 信息校验通过
	if (empty($errors)) {
		$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES
			 ('$fn', '$ln', '$em', SHA1($p), NOW())";
		$r = mysqli_query($dbc, $q);
		if ($r) {
			echo '<h1>谢谢！</h1>
			<p>您已经注册成功</p><p><br /></p>';
		} else {
			echo '<h1>系统错误</h1>
			<p class="error">抱歉，您的注册失败，原因：</p>';
			echo '<p>'.mysqli_error($dbc)
			.'<br /><br />指令: '.$q.'</p>';
		}
		mysqli_close($dbc);
		include ('template/footer.php');
		exit();
	} else {
		echo "<h1>注册信息不正确</h1>";
		echo '<p class="error">发生了以下错误：</p>';
		foreach ($errors as $e) {
			echo ' - '.$e.'<br />';
		}
		echo "<br />请重试。";
	}
	mysqli_close($dbc);
}
?>
<h1>注册新用户</h1>
<form action="register.php" method="POST">
	<p>名字：<input type="text" name="first_name"
	size="15" maxlength="20" value="<?php if(isset($_POST["first_name"]))
	echo $_POST["first_name"];?>" /></p>
	<p>姓氏：<input type="text" name="last_name"
	size="15" maxlength="40" value="<?php if(isset($_POST["last_name"]))
	echo $_POST["last_name"];?>" /></p>
	<p>电子邮箱：<input type="text" name="email"
	size="20" maxlength="60" value="<?php if(isset($_POST["email"]))
	echo $_POST["email"];?>" /></p>
	<p>密码：<input type="password" name="pass1"
	size="10" maxlength="20" /></p>
	<p>确认密码：<input type="password" name="pass2"
	size="10" maxlength="20" /></p>
	<p><input type="submit" name="submit" value="注册"/></p>
</form>
<?php include 'template/footer.php';?>